<template xmlns="http://www.w3.org/1999/html">
  <div style="height: auto; max-width: 100%;" class="box">
    <!--        主页显示区-->
    <div style="height: auto; max-width: 100%;">
      <div style="height: auto; max-width: 100%;">
        <div style="height: auto; max-width: 100%;">
          <div><img style="border-radius: 50%; width:120px" :src="userinfo.avatar"></div>
          <el-button @click="editAvatar">修改头像</el-button>
        </div>
      </div>
      <div style="height: auto; max-width: 100%;" class="desdiv">
        <el-descriptions title="个人信息" :column="1" border>
          <el-descriptions-item label="邮箱账号">{{ userinfo.username }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ userinfo.usernickname }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userinfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ userinfo.userid }}</el-descriptions-item>
          <el-descriptions-item label="校区">
            <el-tag>{{ userinfo.campus }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学院">
            <el-tag type="success">{{ userinfo.academy }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="性別">
            <el-tag type="info">{{ userinfo.sex }}</el-tag>
            <!--                        <el-tag type="warning">标签四</el-tag>-->
            <!--                        <el-tag type="danger">标签五</el-tag>-->
            <!--                        <el-tag size="small">学校</el-tag>-->
          </el-descriptions-item>
          <el-descriptions-item label="微信号">{{ userinfo.wxnamder }}</el-descriptions-item>
          <el-descriptions-item label="个性签名">
            <el-input type="textarea" :disabled="true" v-model="userinfo.signature"></el-input>
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <div>
          <el-button @click="editable()">编辑个人信息</el-button>
        </div>
      </div>
    </div>

    <!--        修改头像框-->
    <el-dialog title="修改头像" :visible.sync="editAvatarDialog" width="100%">
      <el-row type="flex" justify="center">
        <div class="cropper">
          <vueCropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="option.info"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :fixedBox="option.fixedBox"
              @realTime="realTime"
          ></vueCropper>
        </div>
        <div class="previewBox">
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img">
          </div>
          <el-row type="flex" justify="center">
            <el-upload
                action=""
                :show-file-list="false"
                :auto-upload="false"
                :on-change="uploadImg"
            >
              <el-button size="mini" type="primary"
              > 更换头像
              </el-button>
            </el-upload>
          </el-row>
          <br>
          <el-row>
            <el-button icon="el-icon-plus" circle size="mini"
                       @click="changeScale(1)"></el-button>
            <el-button icon="el-icon-minus" circle size="mini"
                       @click="changeScale(-1)"></el-button>
            <el-button icon="el-icon-download" circle size="mini"
                       @click="down('blob')"></el-button>
            <el-button icon="el-icon-refresh-left" circle size="mini"
                       @click="rotateLeft"></el-button>
            <el-button icon="el-icon-refresh-right" circle size="mini"
                       @click="rotateRight"></el-button>
          </el-row>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAvatarDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveEditAvatar">确 定</el-button>
    </span>
    </el-dialog>

    <!--        //未登录的提示框-->
    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="70%"
        center>
      <span style="">还未进行登录！点击下方按钮前往登录</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="FromLogin">前往登录</el-button>
  </span>
    </el-dialog>

    <!--        修改个人信息的对话框-->
    <el-dialog title="编辑用户信息" :visible.sync="dialogFormVisible" width="90%">
      <el-form
          v-loading="loading"
          :model="userinfo"
          ref="userForm"
          label-position="left"
          :rules="rules"
      >
        <el-row>
          <el-col :span="6">
            <span>账号信息：</span>
          </el-col>
          <el-col :span="12">
            <el-input :disabled="true" v-model="userinfo.username"></el-input>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="用户名" prop="usernickname">
              <el-input v-model="userinfo.usernickname"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户电话" prop="phone">
              <el-input v-model="userinfo.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>


          <el-col :span="8">
            <el-select v-model="userinfo.campus" placeholder="请选择校区" prop="Campus">
              <el-option v-for="city in citys" :label="city.name" :value="city.id"
                         :key="city.id"></el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="userinfo.academy" placeholder="请选择学院" prop="academy">
              <el-option v-for="city in citys02" :label="city.name" :value="city.name"
                         :key="city.id"></el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="userinfo.sex" :disabled="true" placeholder="请选择性别" prop="academy">
              <el-option v-for="city in sexs" :label="city.name" :value="city.name"
                         :key="city.id"></el-option>
            </el-select>
          </el-col>

        </el-row>
        <el-row :span="8">
          <el-col :span="8">
            <el-form-item label="学号" prop="userid">
              <el-input :disabled="true" v-model="userinfo.userid"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wxnamder">
              <el-input v-model="userinfo.wxnamder"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="个性签名" prop="signature">
              <el-input type="textarea" v-model="userinfo.signature"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Closetheeditbox()">取 消</el-button>
        <el-button type="primary" @click="updateuserService()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {VueCropper} from 'vue-cropper'
import {getAvatar, getAvatar64, updateuser} from "@/views/personalcenter/personalcenter";
import $axios from "@/api/http";
import response from "core-js/internals/is-forced";


export default {
  name: "index",
  data() {
    return {
      //表单加载显示
      loading: false,
      //校区选择
      citys: [{
        id: '仓山校区',
        name: '仓山校区'
      },
        {
          id: '旗山校区',
          name: '旗山校区'
        },
        {
          id: '海口校区',
          name: '海口校区'
        },

      ],
      //选择性别
      sexs: [{
        id: '男',
        name: '男'
      },
        {
          id: '女',
          name: '女'
        },
      ],
      //学院选择
      citys02: [{
        id: 1,
        name: '数字信息工程学院'
      },
        {
          id: 2,
          name: '人文与管理学院'
        }, {
          id: 3,
          name: '化学与生物技术学院'
        }, {
          id: 4,
          name: '智能制造学院'
        }, {
          id: 5,
          name: '医护学院'
        }, {
          id: 6,
          name: '学前教育学院'
        }, {
          id: 7,
          name: '外语外贸学院'
        }, {
          id: 8,
          name: '小学教育学院'
        }, {
          id: 9,
          name: '艺术学院'
        }
      ],
      formLabelWidth: '120px',
      //是否显示修改个人信息的对话框
      dialogFormVisible: false,
      //是否显示未登录的弹出框
      centerDialogVisible: false,
      //给表单绑定值
      userinfo: {
        //用邮箱账号登录的邮箱
        username: '',
        //姓名
        usernickname: '',
        //手机号码
        phone: '',
        //用户id
        userid: '',
        //校区
        campus: '',
        //学院
        academy: '',
        //性别
        sex: '',
        //微信号
        wxnamder: '',
        //个性签名
        signature: '',
        //头像路径
        avatar: '',
      },
      //部分镜像表单用来提交修改，防止头像的值被覆盖
      userinof: {
        //用户id
        id: '',
        //用邮箱账号登录的邮箱
        username: '',
        //姓名
        usernickname: '',
        //手机号码
        phone: '',
        //用户id
        userid: '',
        //校区
        campus: '',
        //学院
        academy: '',
        //性别
        sex: '',
        //微信号
        wxnamder: '',
        //个性签名
        signature: '',
      },
      //验证输入的内容是否符合要求
      rules: {
        usernickname: [
          {required: true, message: '用户名不可为空', trigger: 'blur',},
          {min: 1, max: 10, message: '长度在 1到 10 个字', trigger: 'blur'},
        ],
        userid: [
          {
            required: true,
            type: 'number',
            message: '请输入正确的学生号',
            trigger: 'blur',
            transform: (value) => Number(value),
          },
          {min: 10, max: 10, message: ' 10 位数字', trigger: 'blur', transform: (value) => String(value)},
        ],
        signature: [
          {required: true, message: '个性签名', trigger: 'blur',},
          {min: 0, max: 30, message: '最长可以输入30字', trigger: 'blur'},
        ],
        phone: [
          {
            required: true,
            type: 'number',
            message: '请输入正确的手机号码',
            trigger: 'blur',
            transform: (value) => Number(value),
          },
          {min: 11, max: 11, message: '11个字符', trigger: 'blur', transform: (value) => String(value),}
        ],
        wxnamder: [
          {required: true, message: '微信账号不可为空', trigger: 'blur',},
          {min: 1, max: 20, message: '最长20个字符', trigger: 'blur'}
        ],

      },
      //是否显示图片裁剪框
      editAvatarDialog: false,
      //保存图片blob对象
      datablob: '',
      previews: {
        url: ''
      },
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        full: true, // 输出原图比例截图 props名full
        outputType: 'png', // 裁剪生成额图片的格式
        canMove: true,  // 能否拖动图片
        original: false,  // 上传图片是否显示原始宽高
        canMoveBox: true,  // 能否拖动截图框
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 150,
        autoCropHeight: 150,
        fixedBox: true // 截图框固定大小
      },
    }
  },
  computed: {},
  beforeMount() {
    this.Loginjudgment()
  },
  mounted: function () {
    this.Displayavatarsbasedongender(this.userinfo.sex)
  }
  ,
  methods: {
    //进行从vuex赋值给userinfo的操作，用来更新
    updatauserinfo() {
      let user = JSON.parse(JSON.stringify(this.$store.state.user))
      user.avatar = this.userinfo.avatar
      this.userinfo = user
    },
    //判断头像地址是否为空，如果为空，但是性别不为空，则按照性别显示头像
    Displayavatarsbasedongender(sex) {
      if (window.sessionStorage.getItem("token") === null) {
        this.userinfo.avatar = require("@/assets/images/个人中心图片.png")
      } else if (this.$store.state.user.avatar === null) {
        if (sex === '男') {
          this.userinfo.avatar = require("@/assets/images/userman.png")
        } else if (sex === '女') {
          this.userinfo.avatar = require("@/assets/images/userwoman.jpg")
        }
      } else {
        getAvatar(this.userinfo.username).then(response => {
          this.userinfo.avatar = response.data.url
        }).catch(error => {
          // 处理错误
          console.error(error);
        });
      }
    },
    //打开loading的方法
    openloding() {
      this.loading = true;
    },
    //关闭loading的方法
    offloading() {
      this.loading = false;
    },
    //更新用户信息的业务逻辑，判断是否有对值进行修改
    updateuserService() {
      if (JSON.stringify(this.userinfo) == JSON.stringify(this.$store.state.user)) {
        this.$message.error('未修改，无需提交！')
      } else {
        this.updateuser()
      }

    },
    //修改用户信息的方法
    updateuser() {
      //给镜像表单赋值
      {
        this.userinof.id = this.$store.state.user.id
        this.userinof.usernickname = this.userinfo.usernickname
        this.userinof.username = this.userinfo.username
        this.userinof.phone = this.userinfo.phone
        this.userinof.userid = this.userinfo.userid
        this.userinof.campus = this.userinfo.campus
        this.userinof.academy = this.userinfo.academy
        this.userinof.sex = this.userinfo.sex
        this.userinof.wxnamder = this.userinfo.wxnamder
        this.userinof.signature = this.userinfo.signature
      }
      updateuser(this.userinof).then(res => {
        // setTimeout(this.offloading(),2000)
        // console.log(res)
        if (res.code === 200) {
          //编辑成功后将新的userinfo表单的值赋值给vuex的SET_INFO
          // this.userinfo.avatar=null
          this.$store.commit("SET_INFO", this.userinof)
          console.log(this.$store.state.imgurl)
          /* // 给头像赋值防止头像重置成默认头像
           if (this.$store.state.user.avatar !== 1) {
               this.$store.state.user.avatar = null
           }*/
          //重新赋值给userinfo表单用来刷新页面（失败的
          this.updatauserinfo()
          this.dialogFormVisible = false
          this.$message.success("修改成功！")
          // this.Displayavatarsbasedongender(this.userinfo.sex)
          setTimeout(() => {
            // 方法区
            //刷新页面的方法
            location.reload()
          }, 1300);
        } else {
          this.$message.error('修改失败！！')
        }
      })
    },
    //关闭编辑框，并让数据恢复未修改的状态
    Closetheeditbox() {
      this.dialogFormVisible = false;
      this.updatauserinfo()
      // console.log(this.$store.getters.getDemoValue)
    },
    //刷新下拉单选框，解决有默认值就无法重新选择的问题
    handleIsopenSelect() {
      this.$forceUpdate()
    },
    //点击编辑时，判断是否已经登录，如果还未登录弹出未登录信息框，如果已经登录就弹出编辑的信息框
    editable() {
      if (window.sessionStorage.getItem("token") === null) {
        this.centerDialogVisible = true;
      } else {
        this.dialogFormVisible = true
      }
    },
    //前往登录页面按钮方法
    FromLogin() {
      this.centerDialogVisible = false
      this.$router.push({
        path: 'login'
      })
    },
    //如果没有token提示未登录,如果有就从userinfo展示数据
    Loginjudgment() {
      // console.log(window.sessionStorage.getItem("token"))
      if (window.sessionStorage.getItem("token") === null) {
        this.centerDialogVisible = true;
      } else {
        this.updatauserinfo()
      }
    },
    //上传头像部分
    editAvatar() {
      if (window.sessionStorage.getItem("token") === null) {
        this.centerDialogVisible = true;
      } else {
        //打开头像编辑框
        this.editAvatarDialog = true
        getAvatar64(this.userinfo.username).then(response => {
          this.option.img ='data:image/png;base64,'+ response.data.url
        }).catch(error => {
          // 处理错误
          console.error(error);
        });
      }
    },
    // 保存头像修改
    saveEditAvatar() {
      this.editAvatarDialog = false
      this.finish('blob')
    },
// 放大/缩小
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
// 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
// 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
// 保存上传图片
    finish(type) {
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          console.log(data)
          //保存图片的地址
          this.userinfo.avatar = window.URL.createObjectURL(data)
          console.log(this.userinfo.avatar)
          //访问接口保存到数据库写这儿!
          const formData = new FormData();
          formData.append('username', this.userinfo.username);
          formData.append('file', data, 'avatar');
          // $axios.post('http://localhost:9999/user/updateuseravatar', formData, {
          $axios.post('http://111.229.186.198:8081/user/updateuseravatar', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response => {
            console.log(response);
            setTimeout(() => {
              // 方法区
              //刷新页面的方法
              location.reload()
            }, 1300);
            this.$store.state.user.avatar = 1
          })
              .catch(error => {
                console.log(error);
              });
        })
      } else {
        this.$refs.cropper.getCropData((data) => {
          //访问接口保存到数据库写这儿!
        })
      }
    },
// 实时预览函数
    realTime(data) {
      this.previews = data
    },
// 下载图片
    down(type) {
      var aLink = document.createElement('a')
      aLink.download = 'author-img'
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          aLink.href = window.URL.createObjectURL(data)
          aLink.click()
        })
      } else {
        this.$refs.cropper.getCropData((data) => {
          aLink.href = data;
          aLink.click()
        })
      }
    },
// 更换头像--上传本地图片
    uploadImg(file) {
      var _this = this;
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === 'object') {
          console.log(e.target.result)
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        _this.option.img = data
      }
      // 转化为base64
      // reader.readAsDataURL(file.raw)
      // 转化为blob
      reader.readAsArrayBuffer(file.raw);
    },
  },
  components: {VueCropper},
}
</script>

<style scoped>
.previewBox {
  text-align: center;
  margin-left: 60px;
}

.preview {
  width: 150px;
  height: 150px;
  margin: 0px auto 20px auto;
  border-radius: 50%;
  border: 1px solid #ccc;
  background-color: #ccc;
  overflow: hidden;
}

.cropper {
  width: 260px;
  height: 260px;
}

.desdiv {
}

.box {
  height: auto;
  max-width: 100%;
  display: flex;
  border: 10px solid rgba(51, 85, 121, 0);
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
  text-align: center;
}

.my-label {
  background: #E1F3D8;
}

.my-content {
  background: #FDE2E2;
}
</style>
